package gdingtalk

import (
	"github.com/astaxie/beego/logs"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"gorm.io/gorm/schema"
)

var (
	db *gorm.DB
)

const (
	StatusWait    = 0
	StatusDoing   = 1
	StatusSuccess = 2
	StatusFail    = 3
)

type OpenSyncBizData struct {
	ID          int64  `json:"id"`
	TableName   string `gorm:"-"`
	GmtCreate   string `json:"gmt_create"`
	GmtModified string `json:"gmt_modified"`
	SubscribeId string `json:"subscribe_id"`
	CorpId      string `json:"corp_id"`
	BizId       string `json:"biz_id"`
	BizType     int64  `json:"biz_type"`
	BizData     string `json:"biz_data"`
	OpenCursor  int64  `json:"open_cursor"`
	// 处理状态，0：未处理，1：处理中，2：处理成功，3：处理失败
	Status int64 `json:"status"`
}

func (o *OpenSyncBizData) UpdateStatus(status int) bool {
	res := db.Table(o.TableName).Where("id = ?", o.ID).Update("status", status)
	if res.RowsAffected > 0 {
		return true
	} else {
		return false
	}
}

func InsertOpenSyncBizData(data []OpenSyncBizData, tableName string) error {
	return db.Table(tableName).Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "subscribe_id"}, {Name: "corp_id"}, {Name: "biz_id"}, {Name: "biz_type"}},
		UpdateAll: true,
	}).Create(&data).Error
}

func initDb(dbConn string) error {
	var err error
	db, err = gorm.Open(mysql.Open(dbConn), &gorm.Config{
		DisableForeignKeyConstraintWhenMigrating: true, NamingStrategy: schema.NamingStrategy{
			SingularTable: true, // 使用单数表名，启用该选项，此时，`User` 的表名应该是 `t_user`
		},
	})
	if err != nil {
		logs.Error("ding_cloud_push database init error: %s", err)
	}
	return err
}
